package com.zhs.demoutil.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhs.demoutil.entity.Admin;
import com.zhs.demoutil.entity.FileRecord;
import com.zhs.demoutil.model.Result;
import com.zhs.demoutil.model.ReturnCode;
import com.zhs.demoutil.model.vo.AdminVO;
import com.zhs.demoutil.model.vo.FileVO;
import com.zhs.demoutil.service.AdminService;
import com.zhs.demoutil.service.FileRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@Api(tags = "文件管理")
@RequestMapping("file")
@Slf4j
public class FileController {

    @Resource
    private FileRecordService fileRecordService;
    @Resource
    private AdminService adminService;

    @ApiOperation("上传文件")
    @PostMapping("upload")
    public Result upload(@RequestParam("file") MultipartFile file){
        String prefix = "/data/file/"+System.currentTimeMillis();
        String filePath = prefix + "/" + file.getOriginalFilename();
        File dest = new File(filePath);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            Subject subject = SecurityUtils.getSubject();
            if(!subject.isAuthenticated()){
                return Result.fail(-1,"需要登陆");
            }
            Object principal = subject.getPrincipal();
            Long adminId = Long.valueOf(principal.toString());
            FileRecord fileRecord = new FileRecord();
            fileRecord.setFileName(file.getOriginalFilename());
            fileRecord.setFilePath(filePath);
            fileRecord.setAdminId(adminId);
            fileRecordService.save(fileRecord);
            return Result.success();
        } catch (IOException e) {
            log.error("文件上传失败",e);
            return Result.fail(-1,"文件上传失败");
        }


    }

    @ApiOperation(value = "文件列表",tags = "列表")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "页码",name = "current",defaultValue = "1"),
            @ApiImplicitParam(value = "每页数量",name = "size",defaultValue = "10")
    })
    @GetMapping("list")
    public Result<Page<FileVO>> list(@RequestParam(defaultValue = "1")Integer current, @RequestParam(defaultValue = "10") Integer size){
        Subject subject = SecurityUtils.getSubject();
        if(!subject.isAuthenticated()){
            return Result.fail(-1,"需要登陆");
        }
        Object principal = subject.getPrincipal();
        Long adminId = Long.valueOf(principal.toString());

        com.baomidou.mybatisplus.extension.plugins.pagination.Page<FileRecord> fileRecordPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size);
        QueryWrapper<FileRecord> fileRecordQueryWrapper = new QueryWrapper<>();
        fileRecordQueryWrapper.eq("adminId",adminId);

        com.baomidou.mybatisplus.extension.plugins.pagination.Page<FileRecord> page = fileRecordService.page(fileRecordPage,fileRecordQueryWrapper);
        List<FileRecord> records = page.getRecords();
        List<FileVO> result = new ArrayList<>();
        for (FileRecord fileRecord : records) {
            FileVO fileVO = new FileVO();
            BeanUtil.copyProperties(fileRecord,fileVO);
            result.add(fileVO);
        }
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<FileVO> adminVOPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>();
        BeanUtil.copyProperties(page,adminVOPage);
        adminVOPage.setRecords(result);
        return Result.success(adminVOPage);

    }

    @PostMapping("delete")
    @ApiOperation("删除")
    public Result delete(@RequestParam Long id){
        fileRecordService.removeById(id);
        return Result.success();
    }

    @ApiOperation("根据自身所属的街道查看对应的文件")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "页码",name = "current",defaultValue = "1"),
            @ApiImplicitParam(value = "每页数量",name = "size",defaultValue = "10")
    })
    @GetMapping("list/by_region_street")
    public Result listByRegionAndStreet(@RequestParam(defaultValue = "1")Integer current, @RequestParam(defaultValue = "10") Integer size){
        Subject subject = SecurityUtils.getSubject();
        if(!subject.isAuthenticated()){
            return Result.fail(-1,"需要登陆");
        }
        Object principal = subject.getPrincipal();
        Long adminId = Long.valueOf(principal.toString());
        Admin byId = adminService.getById(adminId);
        if(Objects.isNull(byId)){
            log.error("管理员不存在");
            return Result.success();
        }
        String region = byId.getRegion();
        String street = byId.getStreet();

        com.baomidou.mybatisplus.extension.plugins.pagination.Page<FileRecord> fileRecordPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size);
        QueryWrapper<FileRecord> fileRecordQueryWrapper = new QueryWrapper<>();
        fileRecordQueryWrapper.eq("region",region);
        fileRecordQueryWrapper.eq("street",street);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<FileRecord> page = fileRecordService.page(fileRecordPage,fileRecordQueryWrapper);
        List<FileRecord> records = page.getRecords();
        List<FileVO> result = new ArrayList<>();
        for (FileRecord fileRecord : records) {
            FileVO fileVO = new FileVO();
            BeanUtil.copyProperties(fileRecord,fileVO);
            result.add(fileVO);
        }
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<FileVO> adminVOPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>();
        BeanUtil.copyProperties(page,adminVOPage);
        adminVOPage.setRecords(result);
        return Result.success(adminVOPage);
    }
    @ApiOperation("根据文件记录id下载文件")
    @GetMapping("/download")
    public void download(@RequestParam Long fileId, HttpServletResponse response) {
        try {
            FileRecord byId = fileRecordService.getById(fileId);
            Assert.notNull(byId,"文件不存在");
            // path是指想要下载的文件的路径
            File file = new File(byId.getFilePath());
            log.info(file.getPath());
            // 获取文件名
            String filename = file.getName();
            // 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            log.info("文件后缀名：" + ext);
            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
// 设置response的Header
            response.setCharacterEncoding("UTF-8");
//Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
//attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
// filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
// 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


}

